import {
  Component,
  OnInit,
  Inject,
  Input,
  Output,
  EventEmitter
} from "@angular/core";
import { RequestOptions } from "@angular/http";

@Component({
  selector: "app-file",
  templateUrl: "./file.component.html",
  styleUrls: ["./file.component.scss"]
})
export class FileComponent implements OnInit {
  files = [];

  @Input()
  lists = [];

  @Output()
  onChange: EventEmitter<any> = new EventEmitter();

  constructor(@Inject("FileService") private fileService) {}

  ngOnInit() {}

  addFile(e) {
    const file = e.target.files[0];
    this.files = this.files.concat(file);
    this.fileService.s3.addFile(file).subscribe(res => {
      this.lists.push({
        ...res.data,
        lastModified: file.lastModified
      });
      this.onChange.emit(this.lists.slice());
    });
  }

  saveLists() {
    this.lists = [];
    for (const item of this.files) {
      const reader = new FileReader();
      reader.readAsDataURL(item);
      const _this = this;
      reader.onload = function() {
        _this.lists.push({
          url: this.result
        });
      };
    }
  }

  delFile(id: string) {
    let ret: any = null;

    for (const item of this.lists) {
      if (item.id === id) {
        ret = item;
      }
    }
    this.lists = this.lists.slice().filter(d => {
      return d.id !== ret.id;
    });

    this.files = this.files.slice().filter(d => {
      return d.lastModified !== ret.lastModified;
    });
    // hare need optmize
    this.onChange.emit(this.lists.slice());
  }

  clear() {
    const lists = this.lists.slice();
    for (let i = 0; i < lists.length; i++) {
      const item = lists[i];
      this.delFile(item.id);
    }
  }
}
